#ifndef MYSERIALWIDGET_H
#define MYSERIALWIDGET_H

#include <QWidget>
#include <QSettings>
#include <QSerialPort>

class MyCommand;

namespace Ui {
class MySerialWidget;
}

class MySerialWidget : public QWidget
{
    Q_OBJECT

public:
    explicit MySerialWidget(QWidget *parent = nullptr);
    ~MySerialWidget();
    void sendCmd(MyCommand &cmd, QWidget *button = nullptr);
    void send(QByteArray &buf);
    void syncSendAndRecv(QByteArray &writtenData, QByteArray &recvData, int &recvLen, QWidget *widget = nullptr);
    void closePort();

    void setMode(int mode);

private:
    Ui::MySerialWidget *ui;

    QSettings *conf;
    QSerialPort *serial;
    QByteArray leftArray;

    char mSerialMode;

    void setupUI();
    QList<QSerialPortInfo> availablePorts();

    bool openPort(QString portname, int baudrate, QString &error);
    void autoConnect();
    void updateUI(bool isConnected);
    void bindRecvEvent();
    void unbindRecvEvent();
    void bindEvents();
    void unbindEvents();
    void asyncSend(QByteArray &writtenData, QWidget *widget = nullptr);

private slots:
    void on_btnRefreshPorts_clicked();

    void on_btnOpenPort_clicked();

    void on_btnClosePort_clicked();

private Q_SLOTS:
    void handleReadyRead();
    void handleBytesWritten(qint64 bytes);
    void handleErrorOccurred(QSerialPort::SerialPortError error);

signals:
    void sign_stateChanged(bool isConnected);
    void sign_dataReaded(QByteArray &data, QByteArray &left);

private:
    QTimer *listPortTimer;
    QTimer *closePortTimer;
private slots:
    void slot_timer_listPort();
    void slot_timer_closePort();
};

#endif // MYSERIALWIDGET_H
